<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 * @author   howe <howe1995@163.com>
 */

namespace App\Support\Traits;

use App\Constant\ApiCodeEnum;
use App\Exception\BusinessException;

trait ServiceException
{
    /**
     * 业务异常返回.
     * @throws BusinessException
     */
    public function throwBusinessException(int|string $code = ApiCodeEnum::FAILED_DEFAULT, string $message = '')
    {
        throw new BusinessException($code, $message);
    }

    /**
     * Note - 解析错误码
     * DateTime 2024/12/19 14:32
     * User Admin.
     * @param mixed $code
     */
    public function parseErrorCode($code)
    {
        if (stripos($code, '|') !== false && empty($message)) {
            $arr = explode('|', $code);
            $code = $arr[0];
        }
        return $code;
    }

    public function parseErrorMessage($code, $message = '')
    {
        if ($message) {
            return $message;
        }
        if (stripos($code, '|') !== false && empty($message)) {
            $arr = explode('|', $code);
            $message = $arr[1];
        }
        empty($message) && $message = '未知错误';
        return $message;
    }
}
